package com.nishop.web.controller;

import com.nishop.api.IGoodsAttrsService;
import com.nishop.api.common.LayuiTableResponse;
import com.nishop.api.common.ResponseBean;
import com.nishop.api.entity.Category;
import com.nishop.api.form.BaseRequestForm;
import com.nishop.web.suport.UploadSuport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/goodsAttrs")
public class GoodsAttrsController {

    @Autowired
    private IGoodsAttrsService iGoodsAttrsService;


    @Value("${server.prefix:}")
    public String serverPrefix;

    @RequestMapping("/index")
    public String index() {

        return "/goodAttrsManage/index";
    }


    @RequestMapping("/edit")
    @ResponseBody
    public ResponseBean<Boolean> edit(Category category,  @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request
    ) {

        String uploadString = UploadSuport.createFileToServer(file, request);
        String uploadPath = serverPrefix + uploadString;
        category.setBannerUrl(uploadPath);
        category.setWapBannerUrl(uploadPath);
        boolean result = iGoodsAttrsService.edit(category);
        return ResponseBean.success(result, result ? "编辑商品类别成功" : "编辑商品类别失败");
    }

    @RequestMapping("/del")
    @ResponseBody
    public ResponseBean<Boolean> del(Category category) {
        boolean result = iGoodsAttrsService.del(category);
        return ResponseBean.success(result, result ? "删除商品类别成功" : "删除商品类别失败");
    }


    @RequestMapping("/add")
    @ResponseBody
    public ResponseBean<Boolean> add(Category category,  @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {

        String uploadString = UploadSuport.createFileToServer(file, request);
        String uploadPath = serverPrefix + uploadString;
        category.setBannerUrl(uploadPath);
        category.setWapBannerUrl(uploadPath);
        boolean result = iGoodsAttrsService.add(category);
        return ResponseBean.success(result, result ? "新增商品类别成功" : "新增商品类别失败");
    }

    /**
     * 查询类目列表
     *
     * @return
     */
    @RequestMapping("/queryLists")
    @ResponseBody
    public LayuiTableResponse<Category> queryGoodsList(BaseRequestForm requestForm) {
        LayuiTableResponse<Category> result = new LayuiTableResponse<>();
        result.setData(iGoodsAttrsService.queryList(requestForm));
        result.setCount(iGoodsAttrsService.queryCount());
        return result;
    }
}
